package com.sticktogether.photoreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.sticktogether.server.ServerCommunication;
import com.sticktogether.services.UploadService;

public class WifiChangeBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// something with the internet connection has changed
		// do we have WIFI now?
		if (checkWifiConnected(context)) {
			// we have WIFI get number of entries in the database for pictures to upload
			PhotoDatabase photoDB = ServerCommunication.getPhotoDb(context);
			SQLiteDatabase db = photoDB.getReadableDatabase();
			Cursor cursor = db.query("photos", null, null, null, null, null, null);
			int size = cursor.getCount();
		    cursor.close();
		    db.close();
		    // are there any pictures to upload?
			if(size!=0) {
				// Start the service for uploading pictures
				Intent Serviceintent = new Intent(context, UploadService.class);
				context.startService(Serviceintent);
			}
		}
	}
	
	/**
	 * This function checks if a WiFi connection is available.
	 * 
	 * @param context: Application context
	 * @return:	true if WIFI is connected
	 * 			false if not
	 */
	public static boolean checkWifiConnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		boolean isConnected = activeNetInfo != null && activeNetInfo.isConnected();
		return isConnected;
	}
	
}